from models.user import User
from utils import result_util


# List all users 查询所有用户
async def list_all() -> list[User]:
    return await User.all()


# 分页查询用户
async def list_with_pagination(query: dict) -> dict:
    name = query.get('name', None)
    page = query.get('page', 1)
    page_size = query.get('page_size', 10)
    offset = (page - 1) * page_size
    query = User.all().offset(offset).limit(page_size)
    if name is not None and name != '':
        query = query.filter(User.username.contains(name))
    user_list = await query
    total = await User.all().count()
    page_total = 0 if total % page_size == 0 else int(total / page_size) + 1
    return result_util.page_table(data=user_list, total=total, page_total=page_total, current_page=page)


# 根据 ID 查询用户
async def get_by_id(user_id: int) -> User:
    return await User.get_or_none(id=user_id)


# 新增用户
async def create_user(user: dict) -> User:
    user = await User.create(username=user['username'], email=user['email'])
    return user


# 修改用户
async def update_user(user: dict) -> User:
    u: User = await User.get(id=user['id'])
    if u is None:
        return User()
    for k, v in user.items():
        setattr(u, k, v)
    await u.save()
    return u


# 删除用户
async def delete_user(user_id: int) -> bool:
    user = await User.get_or_none(id=user_id)
    if user:
        await user.delete()
        return True
    return False
